/*
 * StringInput.cpp
 *
 *  Created on: 18/11/2013
 *      Author: fernando
 */

#include "StringInput.h"
#include <string>
#include "../Interfaz/SDL.h"

using std::string;


const SDL_Color textColor = {0, 0, 0};
const string FONT = "trunk/Fonts/FatMarker.ttf";

StringInput::StringInput(){
    //Initialize the string
    str = "";
    font = TTF_OpenFont(FONT.c_str(), 28);
    //Initialize the surface
    text = NULL;
}

StringInput::~StringInput(){
    //Free text surface
    SDL_FreeSurface( text );
    TTF_CloseFont(font);
}

void StringInput::handle_input(SDL_Event& event){
        //Keep a copy of the current version of the string
        std::string temp = str;
        //If the string less than maximum size
        if(str.length() <= 10){
            //If the key is a space
            if(event.key.keysym.unicode == (Uint16)' '){
                //Append the character
                str += (char)event.key.keysym.unicode;
            }
            //If the key is a number
            else if((event.key.keysym.unicode >= (Uint16)'0') && (event.key.keysym.unicode <= (Uint16)'9')){
                //Append the character
                str += (char)event.key.keysym.unicode;
            }
            //If the key is a uppercase letter
            else if((event.key.keysym.unicode >= (Uint16)'A') && (event.key.keysym.unicode <= (Uint16)'Z')){
                //Append the character
                str += tolower((char)event.key.keysym.unicode);
            }
            //If the key is a lowercase letter
            else if((event.key.keysym.unicode >= (Uint16)'a') && (event.key.keysym.unicode <= (Uint16)'z')){
                //Append the character
                str += (char)event.key.keysym.unicode;
            }
        }

        //If backspace was pressed and the string isn't blank
        if((event.key.keysym.sym == SDLK_BACKSPACE) && (str.length() != 0)){
            //Remove a character from the end
            str.erase(str.length() - 1);
        }

        //If the string was changed
        if(str != temp){
            //Free the old surface
            SDL_FreeSurface(text);
            //Render a new text surface
            text = TTF_RenderText_Solid(font, str.c_str(), textColor);
        }
}

void StringInput::show(unsigned int x, unsigned int y, SDL_Surface* screen){
		//If the surface isn't blank
		if(text != NULL){
			//Show the name
			SDL::apply_surface(x, y, text, screen, NULL);
		}
}

void StringInput::showHidden(unsigned int x, unsigned int y, SDL_Surface* screen){
		//If the surface isn't blank
		string tmp = "";
		if(text != NULL){
			for (unsigned int i = 0; i < str.size(); i++ ){
				tmp += '*';
			}
			SDL_FreeSurface(text);
			//Render a new text surface
			text = TTF_RenderText_Solid(font, tmp.c_str(), textColor);
			//Show the name
			SDL::apply_surface(x, y, text, screen, NULL);
		}
}

TTF_Font* StringInput::getFont(){
	return font;
}

